import { ref, computed, reactive, onMounted, onUnmounted, readonly } from 'vue'
import { ElMessage } from 'element-plus'
import * as fileApi from '@/api/modules/file'
import CryptoJS from 'crypto-js'
import socketManager from '@/utils/socketManager'

// 上传状态枚举
enum UploadStatus {
  IDLE = 'idle',
  PREPARING = 'preparing',
  UPLOADING = 'uploading',
  PAUSED = 'paused',
  COMPLETED = 'completed',
  FAILED = 'failed',
  CANCELLED = 'cancelled'
}

// 上传会话接口
interface UploadSession {
  uploadId: string
  transferRecordId?: number
  file: File
  fileName: string
  fileSize: number
  fileSha256: string
  chunkSize: number
  totalChunks: number
  uploadedChunks: Set<number>
  failedChunks: Set<number>
  parentId?: number
  status: UploadStatus
  progress: number
  uploadedBytes: number
  speed: number
  startTime: number
  lastUpdateTime: number
  needUpload: boolean
  existingFile?: any
}

// 分片上传结果
interface ChunkUploadResult {
  success: boolean
  chunkIndex: number
  uploadedSize: number
  message?: string
}

// 上传配置
interface UploadConfig {
  chunkSize: number
  maxConcurrentChunks: number
  retryAttempts: number
  retryDelay: number
}

export function useFileUpload() {
  // 状态管理
  const isUploading = ref(false)
  const uploadSessions = reactive<Map<string, UploadSession>>(new Map())
  const activeSessionId = ref<string | null>(null)

  // 配置
  const config: UploadConfig = {
    chunkSize: 5 * 1024 * 1024, // 5MB (MinIO要求最小分片大小)
    maxConcurrentChunks: 3,
    retryAttempts: 3,
    retryDelay: 1000
  }

  // Socket.IO事件监听
  const setupSocketListeners = () => {
    // 监听传输进度更新
    socketManager.on('transferProgress', (data) => {
      handleTransferProgress(data)
    })

    // 监听传输完成
    socketManager.on('transferCompleted', (data) => {
      handleTransferCompleted(data)
    })

    // 监听传输失败
    socketManager.on('transferFailed', (data) => {
      handleTransferFailed(data)
    })
  }

  // 清理Socket.IO监听器
  const cleanupSocketListeners = () => {
    socketManager.off('transferProgress')
    socketManager.off('transferCompleted')
    socketManager.off('transferFailed')
  }

  // 处理传输进度更新
  const handleTransferProgress = (data: any) => {
    // console.log('📊 收到传输进度更新:', data)

    // 根据transferRecordId或uploadId查找对应的会话
    const session = findSessionByTransferId(data.transferRecordId) ||
                   findSessionByUploadId(data.uploadId)

    if (session) {
      // 更新会话进度
      session.uploadedBytes = data.uploadedBytes || session.uploadedBytes
      session.progress = data.progress || session.progress
      session.speed = data.speed || session.speed
      session.lastUpdateTime = Date.now()

      // console.log(`📈 更新会话进度: ${session.fileName} - ${session.progress}%`)
    }
  }

  // 处理传输完成
  const handleTransferCompleted = (data: any) => {
    console.log('✅ useFileUpload收到传输完成通知:', data)

    const session = findSessionByTransferId(data.recordId) ||
                   findSessionByUploadId(data.uploadId) ||
                   findSessionByTransferId(data.transferRecordId)

    if (session) {
      session.status = UploadStatus.COMPLETED
      session.progress = 100
      console.log(`🎉 文件上传完成: ${session.fileName}`)

      // 延迟清理会话，让用户能看到完成状态，并确保Socket.IO状态同步
      setTimeout(() => {
        uploadSessions.delete(session.uploadId)
        if (activeSessionId.value === session.uploadId) {
          activeSessionId.value = null
        }
        saveSessionsToStorage()
        console.log(`🧹 已清理完成的上传会话: ${session.fileName}`)
      }, 300) // 0.3秒后清理，快速响应
    } else {
      console.warn('⚠️ 未找到对应的上传会话:', data)
    }
  }

  // 处理传输失败
  const handleTransferFailed = (data: any) => {
    // console.log('❌ 收到传输失败通知:', data)

    const session = findSessionByTransferId(data.transferRecordId) ||
                   findSessionByUploadId(data.uploadId)

    if (session) {
      session.status = UploadStatus.FAILED
      console.log(`文件上传失败: ${session.fileName}`)
      ElMessage.error(`文件上传失败: ${session.fileName}`)
    }
  }

  // 根据transferRecordId查找会话
  const findSessionByTransferId = (transferRecordId: number): UploadSession | undefined => {
    return Array.from(uploadSessions.values()).find(session => session.transferRecordId === transferRecordId)
  }

  // 根据uploadId查找会话
  const findSessionByUploadId = (uploadId: string): UploadSession | undefined => {
    return Array.from(uploadSessions.values()).find(session => session.uploadId === uploadId)
  }
  
  // 状态持久化
  const STORAGE_KEY = 'rickpan_upload_sessions'

  // 保存会话到本地存储
  const saveSessionsToStorage = () => {
    try {
      const sessionsData = Array.from(uploadSessions.entries()).map(([id, session]) => ({
        id,
        session: {
          ...session,
          file: undefined, // 不保存File对象
          uploadedChunks: Array.from(session.uploadedChunks),
          failedChunks: Array.from(session.failedChunks)
        }
      }))
      localStorage.setItem(STORAGE_KEY, JSON.stringify(sessionsData))
    } catch (error) {
      // console.error('保存上传会话失败:', error)
    }
  }

  // 从本地存储恢复会话
  const loadSessionsFromStorage = async () => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      if (stored) {
        const sessionsData = JSON.parse(stored)
        const validSessions: any[] = []

        // 验证每个会话是否在后端仍然存在
        for (const { id, session } of sessionsData) {
          try {
            // 检查后端是否还有这个上传会话
            const response = await fileApi.getUploadProgress(session.uploadId)
            if (response.data) {
              // 恢复Set对象
              session.uploadedChunks = new Set(session.uploadedChunks)
              session.failedChunks = new Set(session.failedChunks)

              // 根据后端状态设置前端状态
              if (response.data.uploadedChunks) {
                session.uploadedChunks = new Set(response.data.uploadedChunks)
                session.uploadedBytes = calculateUploadedBytes(session)
                session.progress = Math.min(100, Math.round((session.uploadedBytes / session.fileSize) * 100))
              }

              // 设置为暂停状态，等待用户手动恢复
              session.status = UploadStatus.PAUSED
              session.lastUpdateTime = Date.now()

              uploadSessions.set(id, session)
              validSessions.push({ id, session })
            }
          } catch (error) {
            // 后端会话不存在，跳过这个会话
            // console.log(`🗑️ 清理已完成的会话: ${session.fileName}`)
          }
        }

        // 更新本地存储，只保留有效会话
        if (validSessions.length !== sessionsData.length) {
          localStorage.setItem(STORAGE_KEY, JSON.stringify(validSessions))
        }

        // console.log(`📂 恢复了 ${validSessions.length} 个有效上传会话`)
      }
    } catch (error) {
      console.error('恢复上传会话失败:', error)
    }
  }

  // 清理本地存储
  const clearSessionsStorage = () => {
    localStorage.removeItem(STORAGE_KEY)
  }

  // 强制同步传输状态
  const syncTransferStatus = async () => {
    try {
      // 请求后端重新发送活跃传输列表
      socketManager.emit('requestActiveTransfers', {})
      // console.log('🔄 请求同步传输状态')
    } catch (error) {
      // console.error('同步传输状态失败:', error)
    }
  }

  // 生命周期管理
  onMounted(() => {
    setupSocketListeners()
    loadSessionsFromStorage()
    setupNetworkRecovery()

    // 延迟同步传输状态，确保Socket连接已建立
    setTimeout(() => {
      syncTransferStatus()
    }, 1000)
  })

  onUnmounted(() => {
    cleanupSocketListeners()
    saveSessionsToStorage()
  })

  // 计算属性
  const currentSession = computed(() => {
    return activeSessionId.value ? uploadSessions.get(activeSessionId.value) : null
  })

  const uploadProgress = computed(() => {
    return currentSession.value?.progress || 0
  })

  const uploadSpeed = computed(() => {
    return currentSession.value?.speed || 0
  })

  /**
   * 计算文件SHA256哈希（优化版本）
   */
  const calculateFileSHA256 = async (file: File, onProgress?: (progress: number) => void): Promise<string> => {
    return new Promise((resolve, reject) => {
      const chunkSize = 1024 * 1024 // 1MB 分块
      const chunks = Math.ceil(file.size / chunkSize)
      let currentChunk = 0

      // console.log(`🔢 开始计算文件哈希: ${file.name}, 大小: ${file.size}, 分块数: ${chunks}`)

      const hasher = CryptoJS.algo.SHA256.create()

      const processChunk = () => {
        if (currentChunk >= chunks) {
          const hash = hasher.finalize().toString()
          // console.log(`✅ 文件哈希计算完成: ${hash}`)
          resolve(hash)
          return
        }

        const start = currentChunk * chunkSize
        const end = Math.min(start + chunkSize, file.size)
        const chunk = file.slice(start, end)

        const reader = new FileReader()
        reader.onload = (e) => {
          try {
            const arrayBuffer = e.target?.result as ArrayBuffer
            const wordArray = CryptoJS.lib.WordArray.create(arrayBuffer)
            hasher.update(wordArray)

            currentChunk++
            const progress = Math.round((currentChunk / chunks) * 100)
            onProgress?.(progress)

            // 使用 setTimeout 避免阻塞UI
            setTimeout(processChunk, 0)
          } catch (error) {
            console.error(`❌ 哈希计算失败 (分块 ${currentChunk}):`, error)
            reject(error)
          }
        }
        reader.onerror = () => {
          reject(new Error(`文件读取失败 (分块 ${currentChunk})`))
        }
        reader.readAsArrayBuffer(chunk)
      }

      processChunk()
    })
  }
  
  /**
   * 计算分片MD5哈希
   */
  const calculateChunkMD5 = async (chunk: Blob): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const arrayBuffer = e.target?.result as ArrayBuffer
          const wordArray = CryptoJS.lib.WordArray.create(arrayBuffer)
          const hash = CryptoJS.MD5(wordArray).toString()
          resolve(hash)
        } catch (error) {
          reject(error)
        }
      }
      reader.onerror = reject
      reader.readAsArrayBuffer(chunk)
    })
  }

  /**
   * 创建上传会话（优化版本）
   */
  const createUploadSession = async (file: File, parentId?: number): Promise<UploadSession> => {
    // 文件大小验证
    if (file.size === 0) {
      throw new Error('文件大小不能为0')
    }

    if (file.size > 10 * 1024 * 1024 * 1024) { // 10GB限制
      throw new Error('文件大小不能超过10GB')
    }

    // console.log(`📝 创建上传会话: ${file.name}, 大小: ${file.size}`)

    // 计算文件哈希
    const fileSha256 = await calculateFileSHA256(file, (progress) => {
      // console.log(`📊 哈希计算进度: ${progress}%`)
    })

    const totalChunks = Math.ceil(file.size / config.chunkSize)
    const uploadId = `upload_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

    const session: UploadSession = {
      uploadId,
      file,
      fileName: file.name,
      fileSize: file.size,
      fileSha256,
      chunkSize: config.chunkSize,
      totalChunks,
      uploadedChunks: new Set(),
      failedChunks: new Set(),
      parentId,
      status: UploadStatus.PREPARING,
      progress: 0,
      uploadedBytes: 0,
      speed: 0,
      startTime: Date.now(),
      lastUpdateTime: Date.now(),
      needUpload: true
    }

    // 初始化后端上传会话
    try {
      const initResponse = await fileApi.initUpload({
        fileName: file.name,
        fileSize: file.size,
        fileSha256,
        chunkSize: config.chunkSize,
        parentId
      })

      session.uploadId = initResponse.data.uploadId
      session.needUpload = initResponse.data.needUpload
      session.existingFile = initResponse.data.existingFile

      if (initResponse.data.uploadedChunks) {
        session.uploadedChunks = new Set(initResponse.data.uploadedChunks)
        // 使用标准算法计算已上传字节数和进度
        session.uploadedBytes = calculateUploadedBytes(session)
        session.progress = Math.min(100, Math.round((session.uploadedBytes / file.size) * 100))
      }

      // console.log(`✅ 上传会话创建成功: ${session.uploadId}, 需要上传: ${session.needUpload}`)

    } catch (error) {
      // console.error('❌ 初始化上传会话失败:', error)
      session.status = UploadStatus.FAILED
      throw new Error(`初始化上传失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }

    return session
  }
  
  /**
   * 计算已上传字节数（与后端算法保持一致）
   */
  const calculateUploadedBytes = (session: UploadSession): number => {
    if (session.uploadedChunks.size === 0) {
      return 0
    }

    let uploadedBytes = session.uploadedChunks.size * session.chunkSize

    // 调整最后一个分片的大小
    if (session.uploadedChunks.has(session.totalChunks - 1)) {
      const lastChunkSize = session.fileSize % session.chunkSize
      if (lastChunkSize > 0) {
        uploadedBytes = uploadedBytes - session.chunkSize + lastChunkSize
      }
    }

    return uploadedBytes
  }

  /**
   * 更新会话进度（使用标准算法）
   */
  const updateSessionProgress = (session: UploadSession) => {
    const previousBytes = session.uploadedBytes

    // 使用标准算法计算已上传字节数
    session.uploadedBytes = calculateUploadedBytes(session)
    session.progress = Math.min(100, Math.round((session.uploadedBytes / session.fileSize) * 100))

    // 计算上传速度
    const now = Date.now()
    const timeDiff = (now - session.lastUpdateTime) / 1000 // 秒

    if (timeDiff > 1 && session.uploadedBytes > previousBytes) { // 至少1秒间隔
      const bytesDiff = session.uploadedBytes - previousBytes
      session.speed = Math.round(bytesDiff / timeDiff)
      session.lastUpdateTime = now
    } else if (session.speed === 0 && session.status === UploadStatus.UPLOADING) {
      // 如果还没有速度数据，给一个估算值
      session.speed = Math.round(session.chunkSize / 2) // 假设2秒上传一个分片
    }

    // console.log(`📊 进度更新: ${session.progress}%, 速度: ${formatSpeed(session.speed)}`)
  }

  /**
   * 格式化速度显示
   */
  const formatSpeed = (bytesPerSecond: number): string => {
    if (bytesPerSecond < 1024) return `${bytesPerSecond} B/s`
    if (bytesPerSecond < 1024 * 1024) return `${(bytesPerSecond / 1024).toFixed(1)} KB/s`
    return `${(bytesPerSecond / (1024 * 1024)).toFixed(1)} MB/s`
  }
  
  /**
   * 上传单个分片（新版本）
   */
  const uploadChunk = async (
    session: UploadSession,
    chunkIndex: number,
    retryCount = 0
  ): Promise<ChunkUploadResult> => {
    try {
      const start = chunkIndex * session.chunkSize
      const end = Math.min(start + session.chunkSize, session.fileSize)
      const chunk = session.file.slice(start, end)

      // 计算分片MD5
      const chunkMd5 = await calculateChunkMD5(chunk)

      // 创建FormData
      const formData = new FormData()
      formData.append('chunk', chunk)
      formData.append('chunkMd5', chunkMd5)

      // console.log(`📤 上传分片 ${chunkIndex + 1}/${session.totalChunks}, 大小: ${chunk.size}`)

      const response = await fileApi.uploadChunk(
        session.uploadId,
        chunkIndex,
        formData
      )

      if (response.data.success) {
        session.uploadedChunks.add(chunkIndex)
        session.failedChunks.delete(chunkIndex)

        // 更新进度
        updateSessionProgress(session)

        // console.log(`✅ 分片 ${chunkIndex + 1} 上传成功`)

        return {
          success: true,
          chunkIndex,
          uploadedSize: chunk.size
        }
      } else {
        throw new Error(response.data.message || '分片上传失败')
      }

    } catch (error) {
      // console.error(`❌ 分片 ${chunkIndex + 1} 上传失败:`, error)

      // 重试逻辑
      if (retryCount < config.retryAttempts) {
        // console.log(`🔄 重试分片 ${chunkIndex + 1}, 第 ${retryCount + 1} 次`)
        await new Promise(resolve => setTimeout(resolve, config.retryDelay))
        return uploadChunk(session, chunkIndex, retryCount + 1)
      }

      session.failedChunks.add(chunkIndex)
      return {
        success: false,
        chunkIndex,
        uploadedSize: 0,
        message: error instanceof Error ? error.message : '未知错误'
      }
    }
  }
  
  /**
   * 并发上传分片（优化版本）
   */
  const uploadChunksConcurrently = async (session: UploadSession): Promise<void> => {
    if (session.status !== UploadStatus.UPLOADING) {
      throw new Error('上传会话状态错误')
    }

    // 获取需要上传的分片
    const chunksToUpload = Array.from({ length: session.totalChunks }, (_, i) => i)
      .filter(index => !session.uploadedChunks.has(index) && !session.failedChunks.has(index))

    if (chunksToUpload.length === 0) {
      // console.log('✅ 所有分片已上传完成')
      return
    }

    // console.log(`📤 开始并发上传 ${chunksToUpload.length} 个分片`)

    // 分批处理，避免创建过多Promise
    const batchSize = config.maxConcurrentChunks
    for (let i = 0; i < chunksToUpload.length; i += batchSize) {
      // 检查是否需要暂停
      if (session.status === UploadStatus.PAUSED) {
        // console.log('⏸️ 上传已暂停')
        break
      }

      const batch = chunksToUpload.slice(i, i + batchSize)
      const batchPromises = batch.map(chunkIndex => uploadChunk(session, chunkIndex))

      try {
        await Promise.allSettled(batchPromises)

        // 保存进度到本地存储
        saveSessionsToStorage()

        // 短暂延迟，避免过于频繁的请求
        if (i + batchSize < chunksToUpload.length) {
          await new Promise(resolve => setTimeout(resolve, 100))
        }
      } catch (error) {
        console.error('批次上传出错:', error)
        // 继续下一批次
      }
    }

    // 检查是否有失败的分片
    if (session.failedChunks.size > 0) {
      console.warn(`⚠️ 有 ${session.failedChunks.size} 个分片上传失败`)
      session.status = UploadStatus.FAILED
      throw new Error(`${session.failedChunks.size} 个分片上传失败`)
    }

    // console.log('✅ 所有分片上传完成')
  }
  
  /**
   * 合并分片
   */
  const mergeChunks = async (session: UploadSession): Promise<any> => {
    try {
      // console.log(`🔗 开始合并分片: ${session.uploadId}`)

      const response = await fileApi.mergeChunks({
        uploadId: session.uploadId,
        fileName: session.fileName,
        parentId: session.parentId
      })

      // console.log('✅ 分片合并成功')
      return response.data
    } catch (error) {
      // console.error('❌ 合并分片失败:', error)
      throw new Error('合并分片失败')
    }
  }

  /**
   * 暂停上传
   */
  const pauseUpload = (sessionId: string) => {
    const session = uploadSessions.get(sessionId)
    if (session && session.status === UploadStatus.UPLOADING) {
      session.status = UploadStatus.PAUSED
      saveSessionsToStorage() // 立即保存状态
      // console.log(`⏸️ 暂停上传: ${session.fileName}`)
      ElMessage.info(`已暂停上传: ${session.fileName}`)
    }
  }

  /**
   * 继续上传
   */
  const resumeUpload = async (sessionId: string, file?: File) => {
    const session = uploadSessions.get(sessionId)
    if (!session || session.status !== UploadStatus.PAUSED) {
      throw new Error('无效的上传会话或状态')
    }

    // 如果没有提供文件对象，需要用户重新选择文件
    if (!session.file && !file) {
      throw new Error('需要重新选择文件以继续上传')
    }

    if (file) {
      // 验证文件是否匹配
      if (file.name !== session.fileName || file.size !== session.fileSize) {
        throw new Error('文件不匹配，无法继续上传')
      }
      session.file = file
    }

    session.status = UploadStatus.UPLOADING
    activeSessionId.value = sessionId
    // console.log(`▶️ 继续上传: ${session.fileName}`)
    ElMessage.info(`继续上传: ${session.fileName}`)

    try {
      await uploadChunksConcurrently(session)

      if (session.uploadedChunks.size === session.totalChunks) {
        session.status = UploadStatus.COMPLETED
        const result = await mergeChunks(session)
        saveSessionsToStorage()
        return result
      }
    } catch (error) {
      session.status = UploadStatus.FAILED
      saveSessionsToStorage()
      throw error
    }
  }

  /**
   * 取消上传
   */
  const cancelUpload = async (sessionId: string) => {
    const session = uploadSessions.get(sessionId)
    if (session) {
      try {
        // 调用后端API清理分片文件和传输记录
        await fileApi.cancelUpload(sessionId)

        session.status = UploadStatus.CANCELLED
        uploadSessions.delete(sessionId)
        saveSessionsToStorage()

        if (activeSessionId.value === sessionId) {
          activeSessionId.value = null
        }

        // console.log(`❌ 取消上传: ${session.fileName}`)
        ElMessage.warning(`已取消上传: ${session.fileName}`)

      } catch (error) {
        // console.error('取消上传失败:', error)
        ElMessage.error('取消上传失败')
      }
    }
  }

  /**
   * 网络状态检测和自动恢复
   */
  const setupNetworkRecovery = () => {
    // 监听网络状态变化
    window.addEventListener('online', () => {
      // console.log('🌐 网络已恢复')
      autoResumeFailedUploads()
    })

    window.addEventListener('offline', () => {
      // console.log('📡 网络已断开')
      pauseAllActiveUploads()
    })
  }

  /**
   * 暂停所有活跃的上传
   */
  const pauseAllActiveUploads = () => {
    uploadSessions.forEach((session, sessionId) => {
      if (session.status === UploadStatus.UPLOADING) {
        pauseUpload(sessionId)
      }
    })
  }

  /**
   * 自动恢复失败的上传
   */
  const autoResumeFailedUploads = () => {
    uploadSessions.forEach((session, sessionId) => {
      if (session.status === UploadStatus.PAUSED || session.status === UploadStatus.FAILED) {
        // 延迟恢复，避免网络刚恢复时的不稳定
        setTimeout(() => {
          if (session.file) {
            resumeUpload(sessionId).catch(error => {
              console.error(`自动恢复上传失败: ${session.fileName}`, error)
            })
          }
        }, 2000)
      }
    })
  }
  
  /**
   * 上传单个文件（新版本）
   */
  const uploadSingleFile = async (
    file: File,
    parentId?: number
  ): Promise<any> => {
    try {
      // 1. 创建上传会话
      const session = await createUploadSession(file, parentId)
      uploadSessions.set(session.uploadId, session)
      activeSessionId.value = session.uploadId

      // console.log(`🚀 开始上传文件: ${session.fileName}`)

      // 2. 检查是否需要上传（文件去重）
      if (!session.needUpload && session.existingFile) {
        session.status = UploadStatus.COMPLETED
        session.progress = 100
        // console.log(`✅ 文件已存在，跳过上传: ${session.fileName}`)
        return session.existingFile
      }

      // 3. 开始上传分片
      session.status = UploadStatus.UPLOADING
      await uploadChunksConcurrently(session)

      // 4. 合并分片
      if (session.uploadedChunks.size === session.totalChunks) {
        const result = await mergeChunks(session)
        session.status = UploadStatus.COMPLETED
        session.progress = 100

        // console.log(`✅ 文件上传完成: ${session.fileName}`)

        // 延迟清理会话，让用户能看到完成状态
        setTimeout(() => {
          uploadSessions.delete(session.uploadId)
          if (activeSessionId.value === session.uploadId) {
            activeSessionId.value = null
          }
          // console.log(`🧹 已清理完成的上传会话: ${session.fileName}`)
        }, 3000) // 3秒后清理

        return result
      } else {
        throw new Error('分片上传不完整')
      }

    } catch (error) {
      console.error(`❌ 文件上传失败: ${file.name}`, error)

      const session = uploadSessions.get(activeSessionId.value!)
      if (session) {
        session.status = UploadStatus.FAILED
      }

      throw error
    }
  }
  
  /**
   * 批量上传文件（新版本）
   */
  const uploadFiles = async (
    files: File[],
    parentId?: number
  ): Promise<any[]> => {
    if (files.length === 0) return []

    isUploading.value = true
    const results: any[] = []

    try {
      // console.log(`📁 开始批量上传 ${files.length} 个文件`)

      for (let i = 0; i < files.length; i++) {
        const file = files[i]

        try {
          const result = await uploadSingleFile(file, parentId)
          results.push(result)

          // console.log(`✅ 文件 ${i + 1}/${files.length} 上传完成: ${file.name}`)

        } catch (error) {
          console.error(`❌ 文件 ${file.name} 上传失败:`, error)
          ElMessage.error(`文件 ${file.name} 上传失败`)
          // 继续上传其他文件
        }
      }

      // console.log(`🎉 批量上传完成，成功: ${results.length}/${files.length}`)
      return results

    } finally {
      isUploading.value = false
    }
  }
  
  /**
   * 获取所有上传会话
   */
  const getAllSessions = () => {
    return Array.from(uploadSessions.values())
  }

  /**
   * 获取指定会话
   */
  const getSession = (sessionId: string) => {
    return uploadSessions.get(sessionId)
  }

  /**
   * 清理已完成的会话
   */
  const cleanupCompletedSessions = () => {
    for (const [sessionId, session] of uploadSessions.entries()) {
      if (session.status === UploadStatus.COMPLETED || session.status === UploadStatus.CANCELLED) {
        uploadSessions.delete(sessionId)
      }
    }
    saveSessionsToStorage()
  }

  /**
   * 获取上传统计信息
   */
  const getUploadStats = () => {
    const sessions = Array.from(uploadSessions.values())
    return {
      total: sessions.length,
      uploading: sessions.filter(s => s.status === UploadStatus.UPLOADING).length,
      paused: sessions.filter(s => s.status === UploadStatus.PAUSED).length,
      completed: sessions.filter(s => s.status === UploadStatus.COMPLETED).length,
      failed: sessions.filter(s => s.status === UploadStatus.FAILED).length,
      cancelled: sessions.filter(s => s.status === UploadStatus.CANCELLED).length
    }
  }

  /**
   * 重试失败的上传
   */
  const retryFailedUpload = async (sessionId: string, file?: File) => {
    const session = uploadSessions.get(sessionId)
    if (!session || session.status !== UploadStatus.FAILED) {
      throw new Error('无效的上传会话或状态')
    }

    // 重置失败状态
    session.status = UploadStatus.PAUSED
    session.failedChunks.clear()

    // 继续上传
    return resumeUpload(sessionId, file)
  }

  /**
   * 暂停所有上传
   */
  const pauseAllUploads = () => {
    uploadSessions.forEach((session, sessionId) => {
      if (session.status === UploadStatus.UPLOADING) {
        pauseUpload(sessionId)
      }
    })
  }

  /**
   * 继续所有暂停的上传
   */
  const resumeAllUploads = async () => {
    const pausedSessions = Array.from(uploadSessions.entries())
      .filter(([_, session]) => session.status === UploadStatus.PAUSED)

    if (pausedSessions.length === 0) {
      ElMessage.info('没有暂停的上传任务')
      return
    }

    // console.log(`🔄 恢复 ${pausedSessions.length} 个暂停的上传`)

    for (const [sessionId, session] of pausedSessions) {
      try {
        if (session.file) {
          await resumeUpload(sessionId)
        } else {
          console.warn(`会话 ${sessionId} 缺少文件对象，跳过恢复`)
        }
      } catch (error) {
        console.error(`恢复上传失败: ${session.fileName}`, error)
      }
    }
  }

  /**
   * 取消所有上传
   */
  const cancelAllUploads = () => {
    const sessionIds = Array.from(uploadSessions.keys())
    sessionIds.forEach(sessionId => {
      cancelUpload(sessionId)
    })
  }

  // 计算属性
  const canUpload = computed(() => !isUploading.value)
  const uploadStatus = computed(() => {
    if (isUploading.value) return 'uploading'
    return 'ready'
  })

  return {
    // 状态
    isUploading: readonly(isUploading),
    uploadProgress,
    uploadSpeed,
    currentSession,
    canUpload,
    uploadStatus,

    // 会话管理
    uploadSessions: readonly(uploadSessions),
    activeSessionId: readonly(activeSessionId),
    getAllSessions,
    getSession,
    cleanupCompletedSessions,
    getUploadStats,

    // 上传方法
    uploadFiles,
    uploadSingleFile,

    // 控制方法
    pauseUpload,
    resumeUpload,
    cancelUpload,
    retryFailedUpload,
    pauseAllUploads,
    resumeAllUploads,
    cancelAllUploads,

    // 状态持久化
    saveSessionsToStorage,
    loadSessionsFromStorage,
    clearSessionsStorage,

    // 工具方法
    formatSpeed,

    // 配置
    config: readonly(config)
  }
}

